<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.4">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.4" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.0.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="开源项目,电商," />


<meta name="description" content="优惠券模块数据库设计优惠券码表coupon_codes表设计：    名称 类型 索引 描述     id int primary key 自增主键   name varchar(50)  优惠券名称   code varchar(50) unique key 优惠码   type tinyint  优惠券类型：固定优惠券 fixed 百分比优惠券 percent,范围：1～99   value">
<meta name="keywords" content="开源项目,电商">
<meta property="og:type" content="article">
<meta property="og:title" content="laravelshop开源项目学习笔记">
<meta property="og:url" content="http://blog.yunshu168.com/posts/7feb99a9.html">
<meta property="og:site_name" content="树下千云">
<meta property="og:description" content="优惠券模块数据库设计优惠券码表coupon_codes表设计：    名称 类型 索引 描述     id int primary key 自增主键   name varchar(50)  优惠券名称   code varchar(50) unique key 优惠码   type tinyint  优惠券类型：固定优惠券 fixed 百分比优惠券 percent,范围：1～99   value">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2020-03-12T07:56:18.452Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="laravelshop开源项目学习笔记">
<meta name="twitter:description" content="优惠券模块数据库设计优惠券码表coupon_codes表设计：    名称 类型 索引 描述     id int primary key 自增主键   name varchar(50)  优惠券名称   code varchar(50) unique key 优惠码   type tinyint  优惠券类型：固定优惠券 fixed 百分比优惠券 percent,范围：1～99   value">






  <link rel="canonical" href="http://blog.yunshu168.com/posts/7feb99a9.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>
  <title>laravelshop开源项目学习笔记 | 树下千云</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f8a99180bb75f49a4b2206cab6e25c50";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <!-- <div class="headband"></div>
<a href="https://github.com/yunshu2009"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">树下千云</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.yunshu168.com/posts/7feb99a9.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="云舒">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="树下千云">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">laravelshop开源项目学习笔记</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <!--<span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>-->
              
                <!--<span class="post-meta-item-text">发表于</span>-->
              
              <!--<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-25T20:37:47+08:00">2019-01-25</time>-->
            

            
            

            
          </span>

          

          
            
          

          
          

          


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="优惠券模块"><a href="#优惠券模块" class="headerlink" title="优惠券模块"></a>优惠券模块</h2><h3 id="数据库设计"><a href="#数据库设计" class="headerlink" title="数据库设计"></a>数据库设计</h3><p>优惠券码表<code>coupon_codes</code>表设计：</p>
<table>
<thead>
<tr>
<th style="text-align:left">名称</th>
<th style="text-align:left">类型</th>
<th style="text-align:left">索引</th>
<th style="text-align:left">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">id</td>
<td style="text-align:left">int</td>
<td style="text-align:left">primary key</td>
<td style="text-align:left">自增主键</td>
</tr>
<tr>
<td style="text-align:left">name</td>
<td style="text-align:left">varchar(50)</td>
<td style="text-align:left"></td>
<td style="text-align:left">优惠券名称</td>
</tr>
<tr>
<td style="text-align:left">code</td>
<td style="text-align:left">varchar(50)</td>
<td style="text-align:left">unique key</td>
<td style="text-align:left">优惠码</td>
</tr>
<tr>
<td style="text-align:left">type</td>
<td style="text-align:left">tinyint</td>
<td style="text-align:left"></td>
<td style="text-align:left">优惠券类型：固定优惠券 fixed 百分比优惠券 percent,范围：1～99</td>
</tr>
<tr>
<td style="text-align:left">value</td>
<td style="text-align:left">decimal(10, 2)</td>
<td style="text-align:left"></td>
<td style="text-align:left">面值</td>
</tr>
<tr>
<td style="text-align:left">total</td>
<td style="text-align:left">int</td>
<td style="text-align:left"></td>
<td style="text-align:left">优惠券总数</td>
</tr>
<tr>
<td style="text-align:left">used</td>
<td style="text-align:left">int</td>
<td style="text-align:left"></td>
<td style="text-align:left">用量</td>
</tr>
<tr>
<td style="text-align:left">min_amount</td>
<td style="text-align:left">decimal(10,2)</td>
<td style="text-align:left"></td>
<td style="text-align:left">最小优惠金额</td>
</tr>
<tr>
<td style="text-align:left">not_before</td>
<td style="text-align:left">timestamp</td>
<td style="text-align:left"></td>
<td style="text-align:left">活动开始时间</td>
</tr>
<tr>
<td style="text-align:left">not_after</td>
<td style="text-align:left">timestamp</td>
<td style="text-align:left"></td>
<td style="text-align:left">活动结束时间</td>
</tr>
<tr>
<td style="text-align:left">enabled</td>
<td style="text-align:left">tinyint(1)</td>
<td style="text-align:left"></td>
<td style="text-align:left">是否开启</td>
</tr>
<tr>
<td style="text-align:left">created_at</td>
<td style="text-align:left">timestamp</td>
<td style="text-align:left"></td>
<td style="text-align:left">创建时间</td>
</tr>
<tr>
<td style="text-align:left">updated_at</td>
<td style="text-align:left">timestamp</td>
<td style="text-align:left"></td>
<td style="text-align:left">修改时间</td>
</tr>
</tbody>
</table>
<a id="more"></a>
<h3 id="程序设计"><a href="#程序设计" class="headerlink" title="程序设计"></a>程序设计</h3><p>优惠码生成代码：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">namespace</span> <span class="title">App</span>\<span class="title">Models</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">use</span> <span class="title">Illuminate</span>\<span class="title">Database</span>\<span class="title">Eloquent</span>\<span class="title">Model</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">Illuminate</span>\<span class="title">Support</span>\<span class="title">Str</span>;</span><br><span class="line">.</span><br><span class="line">.</span><br><span class="line">.</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CouponCode</span> <span class="keyword">extends</span> <span class="title">Model</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">findAvailableCode</span><span class="params">($length = <span class="number">16</span>)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">do</span> &#123;</span><br><span class="line">            <span class="comment">// 生成一个指定长度的随机字符串，并转成大写</span></span><br><span class="line">            $code = strtoupper(Str::random($length));</span><br><span class="line">        <span class="comment">// 如果生成的码已存在就继续循环</span></span><br><span class="line">        &#125; <span class="keyword">while</span> (<span class="keyword">self</span>::query()-&gt;where(<span class="string">'code'</span>, $code)-&gt;exists());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> $code;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="下单逻辑"><a href="#下单逻辑" class="headerlink" title="下单逻辑"></a>下单逻辑</h4><p>OrderController.php:<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">store</span><span class="params">(OrderRequest $request, OrderService $orderService)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    $user    = $request-&gt;user();</span><br><span class="line">    $address = UserAddress::find($request-&gt;input(<span class="string">'address_id'</span>));</span><br><span class="line">    $coupon  = <span class="keyword">null</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 如果用户提交了优惠码</span></span><br><span class="line">    <span class="keyword">if</span> ($code = $request-&gt;input(<span class="string">'coupon_code'</span>)) &#123;</span><br><span class="line">        $coupon = CouponCode::where(<span class="string">'code'</span>, $code)-&gt;first();</span><br><span class="line">        <span class="keyword">if</span> (!$coupon) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> CouponCodeUnavailableException(<span class="string">'优惠券不存在'</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> $orderService-&gt;store($user, $address, $request-&gt;input(<span class="string">'remark'</span>), $request-&gt;input(<span class="string">'items'</span>), $coupon);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>包含了适用优惠券下单逻辑</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">OrderService</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">      <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">store</span><span class="params">(User $user, UserAddress $address, $remark, $items, CouponCode $coupon = null)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> ($coupon) &#123;</span><br><span class="line">            $coupon-&gt;checkAvailable($user);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 开启一个数据库事务</span></span><br><span class="line">        $order = \DB::transaction(<span class="function"><span class="keyword">function</span> <span class="params">()</span> <span class="title">use</span> <span class="params">($user, $address, $remark, $items, $coupon)</span> </span>&#123;</span><br><span class="line">            <span class="comment">// 更新此地址的最后使用时间</span></span><br><span class="line">            $address-&gt;update([<span class="string">'last_used_at'</span> =&gt; Carbon::now()]);</span><br><span class="line">            <span class="comment">// 创建一个订单</span></span><br><span class="line">            $order   = <span class="keyword">new</span> Order([</span><br><span class="line">                <span class="string">'address'</span>      =&gt; [ <span class="comment">// 将地址信息放入订单中</span></span><br><span class="line">                    <span class="string">'address'</span>       =&gt; $address-&gt;full_address,</span><br><span class="line">                    <span class="string">'zip'</span>           =&gt; $address-&gt;zip,</span><br><span class="line">                    <span class="string">'contact_name'</span>  =&gt; $address-&gt;contact_name,</span><br><span class="line">                    <span class="string">'contact_phone'</span> =&gt; $address-&gt;contact_phone,</span><br><span class="line">                ],</span><br><span class="line">                <span class="string">'remark'</span>       =&gt; $remark,</span><br><span class="line">                <span class="string">'total_amount'</span> =&gt; <span class="number">0</span>,</span><br><span class="line">                <span class="string">'type'</span>         =&gt; Order::TYPE_NORMAL,</span><br><span class="line">            ]);</span><br><span class="line">            <span class="comment">// 订单关联到当前用户，保存user_id字段值</span></span><br><span class="line">            $order-&gt;user()-&gt;associate($user);</span><br><span class="line">            <span class="comment">// 写入数据库</span></span><br><span class="line">            $order-&gt;save();</span><br><span class="line"></span><br><span class="line">            $totalAmount = <span class="number">0</span>;</span><br><span class="line">            <span class="comment">// 遍历用户提交的 SKU</span></span><br><span class="line">            <span class="keyword">foreach</span> ($items <span class="keyword">as</span> $data) &#123;</span><br><span class="line">                $sku  = ProductSku::find($data[<span class="string">'sku_id'</span>]);</span><br><span class="line">                <span class="comment">// 创建一个 OrderItem 并直接与当前订单关联</span></span><br><span class="line">                $item = $order-&gt;items()-&gt;make([</span><br><span class="line">                    <span class="string">'amount'</span> =&gt; $data[<span class="string">'amount'</span>],</span><br><span class="line">                    <span class="string">'price'</span>  =&gt; $sku-&gt;price,</span><br><span class="line">                ]);</span><br><span class="line">                <span class="comment">// 给item的product_id字段赋值</span></span><br><span class="line">                $item-&gt;product()-&gt;associate($sku-&gt;product_id);</span><br><span class="line">                <span class="comment">// 给item的product_sku_id字段赋值</span></span><br><span class="line">                $item-&gt;productSku()-&gt;associate($sku);</span><br><span class="line">                $item-&gt;save();</span><br><span class="line">                $totalAmount += $sku-&gt;price * $data[<span class="string">'amount'</span>];</span><br><span class="line">                <span class="keyword">if</span> ($sku-&gt;decreaseStock($data[<span class="string">'amount'</span>]) &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="keyword">throw</span> <span class="keyword">new</span> InvalidRequestException(<span class="string">'该商品库存不足'</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> ($coupon) &#123;</span><br><span class="line">                <span class="comment">// 总金额已经计算出来了，检查是否符合优惠券规则</span></span><br><span class="line">                $coupon-&gt;checkAvailable($user, $totalAmount);</span><br><span class="line">                <span class="comment">// 把订单金额修改为优惠后的金额，按照百分比优惠券或者固定额度优惠券返回新的订单金额</span></span><br><span class="line">                $totalAmount = $coupon-&gt;getAdjustedPrice($totalAmount);</span><br><span class="line">                <span class="comment">// 将订单与优惠券关联，为order表的coupon_code_id字段赋值</span></span><br><span class="line">                $order-&gt;couponCode()-&gt;associate($coupon);</span><br><span class="line">                <span class="comment">// 增加优惠券的用量，需判断返回值</span></span><br><span class="line">                <span class="keyword">if</span> ($coupon-&gt;changeUsed() &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="keyword">throw</span> <span class="keyword">new</span> CouponCodeUnavailableException(<span class="string">'该优惠券已被兑完'</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 更新订单总金额</span></span><br><span class="line">            $order-&gt;update([<span class="string">'total_amount'</span> =&gt; $totalAmount]);</span><br><span class="line">            </span><br><span class="line">            <span class="comment">// 将下单的商品从购物车中移除</span></span><br><span class="line">            $skuIds = collect($items)-&gt;pluck(<span class="string">'sku_id'</span>)-&gt;all();</span><br><span class="line">            app(CartService::class)-&gt;remove($skuIds);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> $order;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 这里我们直接使用 dispatch 函数,超时未支付关闭订单</span></span><br><span class="line">        dispatch(<span class="keyword">new</span> CloseOrder($order, config(<span class="string">'app.order_ttl'</span>)));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> $order;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>重点关注下这几个地方</p>
<h5 id="判断优惠券是否可用"><a href="#判断优惠券是否可用" class="headerlink" title="判断优惠券是否可用"></a>判断优惠券是否可用</h5><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Order</span> <span class="keyword">extends</span> <span class="title">Model</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">checkAvailable</span><span class="params">(User $user, $orderAmount = null)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!<span class="keyword">$this</span>-&gt;enabled) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> CouponCodeUnavailableException(<span class="string">'优惠券不存在'</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">$this</span>-&gt;total - <span class="keyword">$this</span>-&gt;used &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> CouponCodeUnavailableException(<span class="string">'该优惠券已被兑完'</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">$this</span>-&gt;not_before &amp;&amp; <span class="keyword">$this</span>-&gt;not_before-&gt;gt(Carbon::now())) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> CouponCodeUnavailableException(<span class="string">'该优惠券现在还不能使用'</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">$this</span>-&gt;not_after &amp;&amp; <span class="keyword">$this</span>-&gt;not_after-&gt;lt(Carbon::now())) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> CouponCodeUnavailableException(<span class="string">'该优惠券已过期'</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!is_null($orderAmount) &amp;&amp; $orderAmount &lt; <span class="keyword">$this</span>-&gt;min_amount) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> CouponCodeUnavailableException(<span class="string">'订单金额不满足该优惠券最低金额'</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        $used = Order::where(<span class="string">'user_id'</span>, $user-&gt;id)</span><br><span class="line">            -&gt;where(<span class="string">'coupon_code_id'</span>, <span class="keyword">$this</span>-&gt;id)</span><br><span class="line">            -&gt;where(<span class="function"><span class="keyword">function</span><span class="params">($query)</span> </span>&#123;</span><br><span class="line">                $query-&gt;where(<span class="function"><span class="keyword">function</span><span class="params">($query)</span> </span>&#123;</span><br><span class="line">                    $query-&gt;whereNull(<span class="string">'paid_at'</span>)</span><br><span class="line">                        -&gt;where(<span class="string">'closed'</span>, <span class="keyword">false</span>);</span><br><span class="line">                &#125;)-&gt;orWhere(<span class="function"><span class="keyword">function</span><span class="params">($query)</span> </span>&#123;</span><br><span class="line">                    $query-&gt;whereNotNull(<span class="string">'paid_at'</span>)</span><br><span class="line">                        -&gt;where(<span class="string">'refund_status'</span>, <span class="string">'!='</span>, Order::REFUND_STATUS_SUCCESS);</span><br><span class="line">                &#125;);</span><br><span class="line">            &#125;)</span><br><span class="line">            -&gt;exists();</span><br><span class="line">        <span class="keyword">if</span> ($used) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> CouponCodeUnavailableException(<span class="string">'你已经使用过这张优惠券了'</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="消减库存逻辑"><a href="#消减库存逻辑" class="headerlink" title="消减库存逻辑"></a>消减库存逻辑</h5> <figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"> <span class="class"><span class="keyword">class</span> <span class="title">ProductSku</span> <span class="keyword">extends</span> <span class="title">Model</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">      .</span><br><span class="line">      .</span><br><span class="line">      .</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">decreaseStock</span><span class="params">($amount)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> ($amount &lt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> InternalException(<span class="string">'减库存不可小于0'</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;newQuery()-&gt;where(<span class="string">'id'</span>, <span class="keyword">$this</span>-&gt;id)-&gt;where(<span class="string">'stock'</span>, <span class="string">'&gt;='</span>, $amount)-&gt;decrement(<span class="string">'stock'</span>, $amount);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p> 使用到了乐观锁减库存</p>
<h5 id="改变优惠券用量"><a href="#改变优惠券用量" class="headerlink" title="改变优惠券用量"></a>改变优惠券用量</h5> <figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CouponCode</span> <span class="keyword">extends</span> <span class="title">Model</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">     .</span><br><span class="line">     .</span><br><span class="line">     .</span><br><span class="line">     <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">changeUsed</span><span class="params">($increase = true)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// 传入 true 代表新增用量，否则是减少用量</span></span><br><span class="line">        <span class="keyword">if</span> ($increase) &#123;</span><br><span class="line">            <span class="comment">// 与检查 SKU 库存类似，这里需要检查当前用量是否已经超过总量</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;newQuery()-&gt;where(<span class="string">'id'</span>, <span class="keyword">$this</span>-&gt;id)-&gt;where(<span class="string">'used'</span>, <span class="string">'&lt;'</span>, <span class="keyword">$this</span>-&gt;total)-&gt;increment(<span class="string">'used'</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;decrement(<span class="string">'used'</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="秒杀模块"><a href="#秒杀模块" class="headerlink" title="秒杀模块"></a>秒杀模块</h2><h3 id="数据库设计-1"><a href="#数据库设计-1" class="headerlink" title="数据库设计"></a>数据库设计</h3><p>将需要秒杀的商品放到专门的表<code>seckill_products</code>里,表结构如下：</p>
<p>id、product_id、start_at、end_at</p>
<h3 id="程序设计-1"><a href="#程序设计-1" class="headerlink" title="程序设计"></a>程序设计</h3><p>秒杀控制器<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">OrdersController</span> <span class="keyword">extends</span> <span class="title">Controller</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">seckill</span><span class="params">(SeckillOrderRequest $request, OrderService $orderService)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $user = $request-&gt;user();</span><br><span class="line">        $sku  = ProductSku::find($request-&gt;input(<span class="string">'sku_id'</span>));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> $orderService-&gt;seckill($user, $request-&gt;input(<span class="string">'address'</span>), $sku);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="秒杀请求校验"><a href="#秒杀请求校验" class="headerlink" title="秒杀请求校验"></a>秒杀请求校验</h4><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SeckillOrderRequest</span> <span class="keyword">extends</span> <span class="title">Request</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">rules</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> [</span><br><span class="line">            <span class="string">'address.province'</span>      =&gt; <span class="string">'required'</span>,</span><br><span class="line">            <span class="string">'address.city'</span>          =&gt; <span class="string">'required'</span>,</span><br><span class="line">            <span class="string">'address.district'</span>      =&gt; <span class="string">'required'</span>,</span><br><span class="line">            <span class="string">'address.address'</span>       =&gt; <span class="string">'required'</span>,</span><br><span class="line">            <span class="string">'address.zip'</span>           =&gt; <span class="string">'required'</span>,</span><br><span class="line">            <span class="string">'address.contact_name'</span>  =&gt; <span class="string">'required'</span>,</span><br><span class="line">            <span class="string">'address.contact_phone'</span> =&gt; <span class="string">'required'</span>,</span><br><span class="line">            <span class="string">'sku_id'</span>     =&gt; [</span><br><span class="line">                <span class="string">'required'</span>,</span><br><span class="line">                <span class="function"><span class="keyword">function</span> <span class="params">($attribute, $value, $fail)</span> </span>&#123;</span><br><span class="line">                    <span class="comment">// 从 Redis 中读取数据</span></span><br><span class="line">                    $stock = \Redis::get(<span class="string">'seckill_sku_'</span>.$value);</span><br><span class="line">                    <span class="comment">// 如果是 null 代表这个 SKU 不是秒杀商品</span></span><br><span class="line">                    <span class="keyword">if</span> (is_null($stock)) &#123;</span><br><span class="line">                        <span class="keyword">return</span> $fail(<span class="string">'该商品不存在'</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">// 判断库存</span></span><br><span class="line">                    <span class="keyword">if</span> ($stock &lt; <span class="number">1</span>) &#123;</span><br><span class="line">                        <span class="keyword">return</span> $fail(<span class="string">'该商品已售完'</span>);</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">if</span> (!$user = \Auth::user()) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> AuthenticationException(<span class="string">'请先登录'</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">if</span> (!$user-&gt;email_verified) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> InvalidRequestException(<span class="string">'请先验证邮箱'</span>);</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">if</span> ($order = Order::query()</span><br><span class="line">                        <span class="comment">// 筛选出当前用户的订单</span></span><br><span class="line">                        -&gt;where(<span class="string">'user_id'</span>, <span class="keyword">$this</span>-&gt;user()-&gt;id)</span><br><span class="line">                        -&gt;whereHas(<span class="string">'items'</span>, <span class="function"><span class="keyword">function</span> <span class="params">($query)</span> <span class="title">use</span> <span class="params">($value)</span> </span>&#123;</span><br><span class="line">                            <span class="comment">// 筛选出包含当前 SKU 的订单</span></span><br><span class="line">                            $query-&gt;where(<span class="string">'product_sku_id'</span>, $value);</span><br><span class="line">                        &#125;)</span><br><span class="line">                        -&gt;where(<span class="function"><span class="keyword">function</span> <span class="params">($query)</span> </span>&#123;</span><br><span class="line">                            <span class="comment">// 已支付的订单</span></span><br><span class="line">                            $query-&gt;whereNotNull(<span class="string">'paid_at'</span>)</span><br><span class="line">                                <span class="comment">// 或者未关闭的订单</span></span><br><span class="line">                                -&gt;orWhere(<span class="string">'closed'</span>, <span class="keyword">false</span>);</span><br><span class="line">                        &#125;)</span><br><span class="line">                        -&gt;first()) &#123;</span><br><span class="line">                        <span class="keyword">if</span> ($order-&gt;paid_at) &#123;</span><br><span class="line">                            <span class="keyword">return</span> $fail(<span class="string">'你已经抢购了该商品'</span>);</span><br><span class="line">                        &#125;</span><br><span class="line"></span><br><span class="line">                        <span class="keyword">return</span> $fail(<span class="string">'你已经下单了该商品，请到订单页面支付'</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;,</span><br><span class="line">            ],</span><br><span class="line">        ];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>秒杀商品是在后台创建秒杀活动时添加到Redis中的，可以从后台代码中看到如下代码：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SeckillProductsController</span> <span class="keyword">extends</span> <span class="title">CommonProductsController</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">    <span class="keyword">protected</span> <span class="function"><span class="keyword">function</span> <span class="title">customForm</span><span class="params">(Form $form)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// 秒杀相关字段</span></span><br><span class="line">        $form-&gt;datetime(<span class="string">'seckill.start_at'</span>, <span class="string">'秒杀开始时间'</span>)-&gt;rules(<span class="string">'required|date'</span>);</span><br><span class="line">        $form-&gt;datetime(<span class="string">'seckill.end_at'</span>, <span class="string">'秒杀结束时间'</span>)-&gt;rules(<span class="string">'required|date'</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 当商品表单保存完毕时触发</span></span><br><span class="line">        $form-&gt;saved(<span class="function"><span class="keyword">function</span> <span class="params">(Form $form)</span> </span>&#123;</span><br><span class="line">            $product = $form-&gt;model();</span><br><span class="line">            <span class="comment">// 商品重新加载秒杀字段</span></span><br><span class="line">            $product-&gt;load([<span class="string">'seckill'</span>]);</span><br><span class="line">            <span class="comment">// 获取当前时间与秒杀结束时间的差值</span></span><br><span class="line">            $diff = $product-&gt;seckill-&gt;end_at-&gt;getTimestamp() - time();</span><br><span class="line">            <span class="comment">// 遍历商品 SKU</span></span><br><span class="line">            $product-&gt;skus-&gt;each(<span class="function"><span class="keyword">function</span> <span class="params">(ProductSku $sku)</span> <span class="title">use</span> <span class="params">($diff, $product)</span> </span>&#123;</span><br><span class="line">                <span class="comment">// 如果秒杀商品是上架并且尚未到结束时间</span></span><br><span class="line">                <span class="keyword">if</span> ($product-&gt;on_sale &amp;&amp; $diff &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="comment">// 将剩余库存写入到 Redis 中，并设置该值过期时间为秒杀截止时间</span></span><br><span class="line">                    \Redis::setex(<span class="string">'seckill_sku_'</span>.$sku-&gt;id, $diff, $sku-&gt;stock);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="comment">// 否则将该 SKU 的库存值从 Redis 中删除</span></span><br><span class="line">                    \Redis::del(<span class="string">'seckill_sku_'</span>.$sku-&gt;id);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>关键代码<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">\Redis::setex(<span class="string">'seckill_sku_'</span>.$sku-&gt;id, $diff, $sku-&gt;stock);</span><br></pre></td></tr></table></figure></p>
<h4 id="具体秒杀逻辑"><a href="#具体秒杀逻辑" class="headerlink" title="具体秒杀逻辑"></a>具体秒杀逻辑</h4><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">OrderService</span> </span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">seckill</span><span class="params">(User $user, array $addressData, ProductSku $sku)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $order = \DB::transaction(<span class="function"><span class="keyword">function</span> <span class="params">()</span> <span class="title">use</span> <span class="params">($user, $addressData, $sku)</span> </span>&#123;</span><br><span class="line">            <span class="comment">// 创建一个订单</span></span><br><span class="line">            $order = <span class="keyword">new</span> Order([</span><br><span class="line">                <span class="string">'address'</span>      =&gt; [ <span class="comment">// address 字段直接从 $addressData 数组中读取</span></span><br><span class="line">                    <span class="string">'address'</span>       =&gt; $addressData[<span class="string">'province'</span>].$addressData[<span class="string">'city'</span>].$addressData[<span class="string">'district'</span>].$addressData[<span class="string">'address'</span>],</span><br><span class="line">                    <span class="string">'zip'</span>           =&gt; $addressData[<span class="string">'zip'</span>],</span><br><span class="line">                    <span class="string">'contact_name'</span>  =&gt; $addressData[<span class="string">'contact_name'</span>],</span><br><span class="line">                    <span class="string">'contact_phone'</span> =&gt; $addressData[<span class="string">'contact_phone'</span>],</span><br><span class="line">                ],</span><br><span class="line">                <span class="string">'remark'</span>       =&gt; <span class="string">''</span>,</span><br><span class="line">                <span class="string">'total_amount'</span> =&gt; $sku-&gt;price,</span><br><span class="line">                <span class="string">'type'</span>         =&gt; Order::TYPE_SECKILL,</span><br><span class="line">            ]);</span><br><span class="line">            <span class="comment">// 订单关联到当前用户,包含user_id</span></span><br><span class="line">            $order-&gt;user()-&gt;associate($user);</span><br><span class="line">            <span class="comment">// 写入数据库</span></span><br><span class="line">            $order-&gt;save();</span><br><span class="line">            <span class="comment">// 创建一个新的订单项并与 SKU 关联</span></span><br><span class="line">            $item = $order-&gt;items()-&gt;make([</span><br><span class="line">                <span class="string">'amount'</span> =&gt; <span class="number">1</span>, <span class="comment">// 秒杀商品只能一份</span></span><br><span class="line">                <span class="string">'price'</span>  =&gt; $sku-&gt;price,</span><br><span class="line">            ]);</span><br><span class="line">            <span class="comment">// 保存product_id</span></span><br><span class="line">            $item-&gt;product()-&gt;associate($sku-&gt;product_id);</span><br><span class="line">            <span class="comment">// 保存product_sku_id</span></span><br><span class="line">            $item-&gt;productSku()-&gt;associate($sku);</span><br><span class="line">            $item-&gt;save();</span><br><span class="line">            <span class="comment">// 扣减对应 SKU 库存</span></span><br><span class="line">            <span class="keyword">if</span> ($sku-&gt;decreaseStock(<span class="number">1</span>) &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> InvalidRequestException(<span class="string">'该商品库存不足'</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            \Redis::decr(<span class="string">'seckill_sku_'</span>.$sku-&gt;id);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> $order;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="comment">// 秒杀订单的自动关闭时间与普通订单不同</span></span><br><span class="line">        dispatch(<span class="keyword">new</span> CloseOrder($order, config(<span class="string">'app.seckill_order_ttl'</span>)));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> $order;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里注意下扣减扣存逻辑使用到了乐观锁应对高并发请求，具体代码上面展示过。另外还从redis将库存削减了，代码：<code>\Redis::decr(&#39;seckill_sku_&#39;.$sku-&gt;id);</code>。秒杀自动关闭的时间和普通订单时间不一样，更短一些，所以做了另外配置<code>config(&#39;app.seckill_order_ttl&#39;)</code>。</p>
<h2 id="商品搜索模块"><a href="#商品搜索模块" class="headerlink" title="商品搜索模块"></a>商品搜索模块</h2><p>后台添加商品之后将商品添加到 ElasticSearch 中:</p>
<p>Admin/Controllers/CommonController.php</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">CommonProductsController</span> <span class="keyword">extends</span> <span class="title">Controller</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    <span class="keyword">protected</span> <span class="function"><span class="keyword">function</span> <span class="title">form</span><span class="params">()</span></span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    <span class="comment">// 商品保存时添加到ES中</span></span><br><span class="line">    $form-&gt;saved(<span class="function"><span class="keyword">function</span> <span class="params">(Form $form)</span> </span>&#123;</span><br><span class="line">       $product = $form-&gt;model();</span><br><span class="line">        <span class="keyword">$this</span>-&gt;dispatch(<span class="keyword">new</span> SyncOneProductToES($product));</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">   <span class="keyword">return</span> $form;</span><br><span class="line">  &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>app\Jobs\SyncOneProductToES.php</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SyncOneProductToES</span> <span class="keyword">implements</span> <span class="title">ShouldQueue</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="keyword">use</span> <span class="title">Dispatchable</span>, <span class="title">InteractsWithQueue</span>, <span class="title">Queueable</span>, <span class="title">SerializesModels</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">protected</span> $product;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">__construct</span><span class="params">(Product $product)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">$this</span>-&gt;product = $product;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">handle</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $data = <span class="keyword">$this</span>-&gt;product-&gt;toESArray();</span><br><span class="line">        <span class="comment">// 索引商品数据  app('es')为使用 elasticsearch/elasticsearch 包创建的 ES实例</span></span><br><span class="line">        app(<span class="string">'es'</span>)-&gt;index([</span><br><span class="line">            <span class="string">'index'</span> =&gt; <span class="string">'products'</span>,</span><br><span class="line">            <span class="string">'type'</span>  =&gt; <span class="string">'_doc'</span>,</span><br><span class="line">            <span class="string">'id'</span>    =&gt; $data[<span class="string">'id'</span>],</span><br><span class="line">            <span class="string">'body'</span>  =&gt; $data,</span><br><span class="line">        ]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>$data 数据：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Product</span> <span class="keyword">extends</span> <span class="title">Model</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">toESArray</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// 只取出需要的字段</span></span><br><span class="line">        $arr = array_only(<span class="keyword">$this</span>-&gt;toArray(), [</span><br><span class="line">            <span class="string">'id'</span>,</span><br><span class="line">            <span class="string">'type'</span>,</span><br><span class="line">            <span class="string">'title'</span>,</span><br><span class="line">            <span class="string">'category_id'</span>,</span><br><span class="line">            <span class="string">'long_title'</span>,</span><br><span class="line">            <span class="string">'on_sale'</span>,</span><br><span class="line">            <span class="string">'rating'</span>,</span><br><span class="line">            <span class="string">'sold_count'</span>,</span><br><span class="line">            <span class="string">'review_count'</span>,</span><br><span class="line">            <span class="string">'price'</span>,</span><br><span class="line">        ]);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 如果商品有类目，则 category 字段为类目名数组，否则为空字符串</span></span><br><span class="line">        $arr[<span class="string">'category'</span>] = <span class="keyword">$this</span>-&gt;category ? explode(<span class="string">' - '</span>, <span class="keyword">$this</span>-&gt;category-&gt;full_name) : <span class="string">''</span>;</span><br><span class="line">        <span class="comment">// 类目的 path 字段</span></span><br><span class="line">        $arr[<span class="string">'category_path'</span>] = <span class="keyword">$this</span>-&gt;category ? <span class="keyword">$this</span>-&gt;category-&gt;path : <span class="string">''</span>;</span><br><span class="line">        <span class="comment">// strip_tags 函数可以将 html 标签去除</span></span><br><span class="line">        $arr[<span class="string">'description'</span>] = strip_tags(<span class="keyword">$this</span>-&gt;description);</span><br><span class="line">        <span class="comment">// 只取出需要的 SKU 字段</span></span><br><span class="line">        $arr[<span class="string">'skus'</span>] = <span class="keyword">$this</span>-&gt;skus-&gt;map(<span class="function"><span class="keyword">function</span> <span class="params">(ProductSku $sku)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> array_only($sku-&gt;toArray(), [<span class="string">'title'</span>, <span class="string">'description'</span>, <span class="string">'price'</span>]);</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="comment">// 只取出需要的商品属性字段</span></span><br><span class="line">        $arr[<span class="string">'properties'</span>] = <span class="keyword">$this</span>-&gt;properties-&gt;map(<span class="function"><span class="keyword">function</span> <span class="params">(ProductProperty $property)</span> </span>&#123;</span><br><span class="line">            <span class="comment">// 对应地增加一个 search_value 字段，用符号 : 将属性名和属性值拼接起来</span></span><br><span class="line">            <span class="keyword">return</span> array_merge(array_only($property-&gt;toArray(), [<span class="string">'name'</span>, <span class="string">'value'</span>]), [</span><br><span class="line">                <span class="string">'search_value'</span> =&gt; $property-&gt;name.<span class="string">':'</span>.$property-&gt;value,</span><br><span class="line">            ]);</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> $arr;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>前台就可以使用标题、类别、描述、属性值、分类作为搜索条件搜索了：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ProductsController</span> <span class="keyword">extends</span> <span class="title">Controller</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">index</span><span class="params">(Request $request)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $page    = $request-&gt;input(<span class="string">'page'</span>, <span class="number">1</span>);</span><br><span class="line">        $perPage = <span class="number">16</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 新建查询构造器对象，设置只搜索上架商品，设置分页</span></span><br><span class="line">        $builder = (<span class="keyword">new</span> ProductSearchBuilder())-&gt;onSale()-&gt;paginate($perPage, $page);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> ($search = $request-&gt;input(<span class="string">'search'</span>, <span class="string">''</span>)) &#123;</span><br><span class="line">            $keywords = array_filter(explode(<span class="string">' '</span>, $search));</span><br><span class="line">            <span class="comment">// 调用查询构造器的关键词筛选</span></span><br><span class="line">            $builder-&gt;keywords($keywords);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> ($search || <span class="keyword">isset</span>($category)) &#123;</span><br><span class="line">            <span class="comment">// 调用查询构造器的分面搜索</span></span><br><span class="line">            $builder-&gt;aggregateProperties();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> ($request-&gt;input(<span class="string">'category_id'</span>) &amp;&amp; $category = Category::find($request-&gt;input(<span class="string">'category_id'</span>))) &#123;</span><br><span class="line">            <span class="comment">// 调用查询构造器的类目筛选</span></span><br><span class="line">            $builder-&gt;category($category);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 从用户请求参数获取 filters</span></span><br><span class="line">        $propertyFilters = [];</span><br><span class="line">        <span class="keyword">if</span> ($filterString = $request-&gt;input(<span class="string">'filters'</span>)) &#123;</span><br><span class="line">            <span class="comment">// 将获取到的字符串用符号 | 拆分成数组</span></span><br><span class="line">            $filterArray = explode(<span class="string">'|'</span>, $filterString);</span><br><span class="line">            <span class="keyword">foreach</span> ($filterArray <span class="keyword">as</span> $filter) &#123;</span><br><span class="line">                <span class="comment">// 将字符串用符号 : 拆分成两部分并且分别赋值给 $name 和 $value 两个变量</span></span><br><span class="line">                <span class="keyword">list</span>($name, $value) = explode(<span class="string">':'</span>, $filter);</span><br><span class="line">                <span class="comment">// 将用户筛选的属性添加到数组中</span></span><br><span class="line">                $propertyFilters[$name] = $value;</span><br><span class="line">                <span class="comment">// 调用查询构造器的属性筛选</span></span><br><span class="line">                $builder-&gt;propertyFilter($name, $value);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 是否有提交 order 参数，如果有就赋值给 $order 变量</span></span><br><span class="line">        <span class="comment">// order 参数用来控制商品的排序规则</span></span><br><span class="line">        <span class="keyword">if</span> ($order = $request-&gt;input(<span class="string">'order'</span>, <span class="string">''</span>)) &#123;</span><br><span class="line">            <span class="comment">// 是否是以 _asc 或者 _desc 结尾</span></span><br><span class="line">            <span class="keyword">if</span> (preg_match(<span class="string">'/^(.+)_(asc|desc)$/'</span>, $order, $m)) &#123;</span><br><span class="line">                <span class="comment">// 如果字符串的开头是这 3 个字符串之一，说明是一个合法的排序值</span></span><br><span class="line">                <span class="keyword">if</span> (in_array($m[<span class="number">1</span>], [<span class="string">'price'</span>, <span class="string">'sold_count'</span>, <span class="string">'rating'</span>])) &#123;</span><br><span class="line">                    <span class="comment">// 调用查询构造器的排序</span></span><br><span class="line">                    $builder-&gt;orderBy($m[<span class="number">1</span>], $m[<span class="number">2</span>]);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        $result = app(<span class="string">'es'</span>)-&gt;search($builder-&gt;getParams());</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 通过 collect 函数将返回结果转为集合，并通过集合的 pluck 方法取到返回的商品 ID 数组</span></span><br><span class="line">        $productIds = collect($result[<span class="string">'hits'</span>][<span class="string">'hits'</span>])-&gt;pluck(<span class="string">'_id'</span>)-&gt;all();</span><br><span class="line">        <span class="comment">// 通过 whereIn 方法从数据库中读取商品数据</span></span><br><span class="line">        $products = Product::query()-&gt;byIds($productIds)-&gt;get();</span><br><span class="line">        <span class="comment">// 返回一个 LengthAwarePaginator 对象</span></span><br><span class="line">        $pager = <span class="keyword">new</span> LengthAwarePaginator($products, $result[<span class="string">'hits'</span>][<span class="string">'total'</span>], $perPage, $page, [</span><br><span class="line">            <span class="string">'path'</span> =&gt; route(<span class="string">'products.index'</span>, <span class="keyword">false</span>), <span class="comment">// 手动构建分页的 url</span></span><br><span class="line">        ]);</span><br><span class="line"></span><br><span class="line">        $properties = [];</span><br><span class="line">        <span class="comment">// 如果返回结果里有 aggregations 字段，说明做了分面搜索</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">isset</span>($result[<span class="string">'aggregations'</span>])) &#123;</span><br><span class="line">            <span class="comment">// 使用 collect 函数将返回值转为集合</span></span><br><span class="line">            $properties = collect($result[<span class="string">'aggregations'</span>][<span class="string">'properties'</span>][<span class="string">'properties'</span>][<span class="string">'buckets'</span>])</span><br><span class="line">                -&gt;map(<span class="function"><span class="keyword">function</span> <span class="params">($bucket)</span> </span>&#123;</span><br><span class="line">                    <span class="comment">// 通过 map 方法取出我们需要的字段</span></span><br><span class="line">                    <span class="keyword">return</span> [</span><br><span class="line">                        <span class="string">'key'</span>    =&gt; $bucket[<span class="string">'key'</span>],</span><br><span class="line">                        <span class="string">'values'</span> =&gt; collect($bucket[<span class="string">'value'</span>][<span class="string">'buckets'</span>])-&gt;pluck(<span class="string">'key'</span>)-&gt;all(),</span><br><span class="line">                    ];</span><br><span class="line">                &#125;)</span><br><span class="line">                -&gt;filter(<span class="function"><span class="keyword">function</span> <span class="params">($property)</span> <span class="title">use</span> <span class="params">($propertyFilters)</span> </span>&#123;</span><br><span class="line">                    <span class="comment">// 过滤掉只剩下一个值 或者 已经在筛选条件里的属性</span></span><br><span class="line">                    <span class="keyword">return</span> count($property[<span class="string">'values'</span>]) &gt; <span class="number">1</span> &amp;&amp; !<span class="keyword">isset</span>($propertyFilters[$property[<span class="string">'key'</span>]]) ;</span><br><span class="line">                &#125;);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> view(<span class="string">'products.index'</span>, [</span><br><span class="line">            <span class="string">'products'</span> =&gt; $pager,</span><br><span class="line">            <span class="string">'filters'</span>  =&gt; [</span><br><span class="line">                <span class="string">'search'</span> =&gt; $search,</span><br><span class="line">                <span class="string">'order'</span>  =&gt; $order,</span><br><span class="line">            ],</span><br><span class="line">            <span class="string">'category'</span> =&gt; $category ?? <span class="keyword">null</span>,</span><br><span class="line">            <span class="string">'properties'</span> =&gt; $properties,</span><br><span class="line">            <span class="string">'propertyFilters'</span> =&gt; $propertyFilters,</span><br><span class="line">        ]);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>具体查看laravelshop的代码</p>
<h2 id="其它"><a href="#其它" class="headerlink" title="其它"></a>其它</h2><h3 id="订单表订单号生成方案"><a href="#订单表订单号生成方案" class="headerlink" title="订单表订单号生成方案"></a>订单表订单号生成方案</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">namespace</span> <span class="title">App</span>\<span class="title">Models</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">use</span> <span class="title">Illuminate</span>\<span class="title">Database</span>\<span class="title">Eloquent</span>\<span class="title">Model</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">Ramsey</span>\<span class="title">Uuid</span>\<span class="title">Uuid</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Order</span> <span class="keyword">extends</span> <span class="title">Model</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">        .</span><br><span class="line">        <span class="comment">// 订单号</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">findAvailableNo</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// 订单流水号前缀</span></span><br><span class="line">        $prefix = date(<span class="string">'YmdHis'</span>);</span><br><span class="line">        <span class="keyword">for</span> ($i = <span class="number">0</span>; $i &lt; <span class="number">10</span>; $i++) &#123;</span><br><span class="line">            <span class="comment">// 随机生成 6 位的数字</span></span><br><span class="line">            $no = $prefix.str_pad(random_int(<span class="number">0</span>, <span class="number">999999</span>), <span class="number">6</span>, <span class="string">'0'</span>, STR_PAD_LEFT);</span><br><span class="line">            <span class="comment">// 判断是否已经存在</span></span><br><span class="line">            <span class="keyword">if</span> (!<span class="keyword">static</span>::query()-&gt;where(<span class="string">'no'</span>, $no)-&gt;exists()) &#123;</span><br><span class="line">                <span class="keyword">return</span> $no;</span><br><span class="line">            &#125;</span><br><span class="line">            usleep(<span class="number">100</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        \Log::warning(sprintf(<span class="string">'find order no failed'</span>));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 退款单号</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">getAvailableRefundNo</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">do</span> &#123;</span><br><span class="line">            <span class="comment">// Uuid类可以用来生成大概率不重复的字符串</span></span><br><span class="line">            $no = Uuid::uuid4()-&gt;getHex();</span><br><span class="line">            <span class="comment">// 为了避免重复我们在生成之后在数据库中查询看看是否已经存在相同的退款订单号</span></span><br><span class="line">        &#125; <span class="keyword">while</span> (<span class="keyword">self</span>::query()-&gt;where(<span class="string">'refund_no'</span>, $no)-&gt;exists());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> $no;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个订单号生产方案虽然不完美，但是确实能保证订单号唯一。</p>
<h3 id="拓展资料"><a href="#拓展资料" class="headerlink" title="拓展资料"></a>拓展资料</h3><p>秒杀一个更为推荐的一个方案时使用Redis分布式锁+消息队列处理高并发问题，参考资料：<br><a href="https://learnku.com/articles/28245" target="_blank" rel="noopener">秒杀系统的设计</a></p>
<p>秒杀系统设计与实现.互联网工程师进阶与分析：<a href="https://github.com/qiurunze123/miaosha/tree/master/docs" target="_blank" rel="noopener">https://github.com/qiurunze123/miaosha/tree/master/docs</a> </p>

      
    </div>

    

    
    
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------本文结束<i class="fa fa-paw"></i>感谢阅读------</div>
    
</div>
  
</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欣赏此文？求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="云舒 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="云舒 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>云舒</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.yunshu168.com/posts/7feb99a9.html" title="laravelshop开源项目学习笔记">http://blog.yunshu168.com/posts/7feb99a9.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/开源项目/" rel="tag"># 开源项目</a>
          
            <a href="/tags/电商/" rel="tag"># 电商</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/ba8c712f.html" rel="next" title="微信小程序授权登录实例">
                <i class="fa fa-chevron-left"></i> 微信小程序授权登录实例
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/29036118.html" rel="prev" title="在 PHP 中执行 JS 代码">
                在 PHP 中执行 JS 代码 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="云舒" />
            
              <p class="site-author-name" itemprop="name">云舒</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">68</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">28</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yunshu2009" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yunshu.luo@gmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.cnblogs.com/luoyunshu/" target="_blank" title="Cnblogs"><i class="fa fa-fw fa-globe"></i>Cnblogs</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.bilibili.com" target="_blank" title="bilibili"><i class="fa fa-fw fa-globe"></i>bilibili</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#优惠券模块"><span class="nav-number">1.</span> <span class="nav-text">优惠券模块</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#数据库设计"><span class="nav-number">1.1.</span> <span class="nav-text">数据库设计</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#程序设计"><span class="nav-number">1.2.</span> <span class="nav-text">程序设计</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#下单逻辑"><span class="nav-number">1.2.1.</span> <span class="nav-text">下单逻辑</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#判断优惠券是否可用"><span class="nav-number">1.2.1.1.</span> <span class="nav-text">判断优惠券是否可用</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#消减库存逻辑"><span class="nav-number">1.2.1.2.</span> <span class="nav-text">消减库存逻辑</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#改变优惠券用量"><span class="nav-number">1.2.1.3.</span> <span class="nav-text">改变优惠券用量</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#秒杀模块"><span class="nav-number">2.</span> <span class="nav-text">秒杀模块</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#数据库设计-1"><span class="nav-number">2.1.</span> <span class="nav-text">数据库设计</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#程序设计-1"><span class="nav-number">2.2.</span> <span class="nav-text">程序设计</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#秒杀请求校验"><span class="nav-number">2.2.1.</span> <span class="nav-text">秒杀请求校验</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#具体秒杀逻辑"><span class="nav-number">2.2.2.</span> <span class="nav-text">具体秒杀逻辑</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#商品搜索模块"><span class="nav-number">3.</span> <span class="nav-text">商品搜索模块</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其它"><span class="nav-number">4.</span> <span class="nav-text">其它</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#订单表订单号生成方案"><span class="nav-number">4.1.</span> <span class="nav-text">订单表订单号生成方案</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#拓展资料"><span class="nav-number">4.2.</span> <span class="nav-text">拓展资料</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2012 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">云舒</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a></div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.4"></script>



  



	





  





  






<!-- LOCAL: You can save these files to your site and update links -->
    
        
         <!-- <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css"> -->
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/default.css">
        <script src="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/gitment.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: decodeURI(window.location.pathname),
            owner: 'yunshu2009',
            repo: 'yunshu2009.github.io',
            
            oauth: {
            
            
                client_secret: '15cdd9dc30fb9e0c97260bf79fe09d158fa04b22',
            
                client_id: '9495da16cda475a5e221'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


</body>
</html>
